<template>
    <div>
        <div class="operation-group">
            <acceptListSelect
                btnText="选择验收单"
                dialogTitle="选择验收单"
                :searchInputArr="jsList.planSearchInputArr"
                :tableHeadOptions="jsList.acceptTableHeadOptions"
                :settlement-form="settlementForm"
                @numrow="numrow"
            />
            
            <!--      <el-button-->
            <!--        plain-->
            <!--        type="single-number"-->
            <!--        :style="{ marginLeft: '10px' }"-->
            <!--        @click="dialogVisible = true"-->
            <!--      >-->
            <!--        批量操作-->
            <!--      </el-button>-->
            
            <el-dialog
                title="批量操作"
                :visible.sync="dialogVisible"
                width="400px"
                :before-close="handleClose"
            >
                <div class="el-dialog__body-bodys">
                    <el-form :model="form" ref="form" class="ccui-form">
                        <el-form-item label="生产厂家/品牌：" prop="brand">
                            <el-input
                                v-model="form.brand"
                                placeholder="请输入生产厂家/品牌"
                            ></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button
                        size="mini"
                        type="default-mini"
                        @click="dialogVisible = false"
                    >取消
                    </el-button>
                    <el-button size="mini" type="primary-font-mini" @click="btnModify()"
                    >确定
                    </el-button>
                </div>
            </el-dialog>
            <el-dropdown
                plain
                type="single-number"
                placement="bottom"
                trigger="click"
                @command="batchOperate"
                style="margin-left: 10px"
            >
                <el-button class="search-btn" size="mini">
                    其他费用项
                    <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="btn-interest">贴息</el-dropdown-item>
                    <el-dropdown-item command="btn-priceRise">价格追涨</el-dropdown-item>
                    <el-dropdown-item command="btn-priceFall">价格追跌</el-dropdown-item>
                    <el-dropdown-item command="btn-priceOther">其他</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            <el-button plain type="single-number" @click="hebingFunAuto"
            >合并
            </el-button
            >
            <!--      <el-button class="ml" plain type="single-number" @click="handleCopy"-->
            <!--        >复制行-->
            <!--      </el-button>-->
            
            <el-button class="deleteLine" @click="handleDelete">删除行</el-button>
            <!-- :getTableList="listPursckinfoPage" -->
        </div>
        <div class="ccui-multifunctional-table-wrapper">
            <ux-grid
                class="ccui-form-child-table"
                keep-source
                widthResize
                width="100%"
                show-overflow="title"
                show-summary
                :summary-method="getSummaries"
                @select="listSelectTable"
                @select-all="listSelectTable"
                @selection-change="handleSelectionChange"
                :edit-config="{ trigger: 'click', mode: 'cell' }"
                ref="tableList"
                :checkboxConfig="{ checkMethod: handleSelectableDisabled, highlight: false }"
            >
                
                <ux-table-column
                    type="checkbox"
                    width="55"
                    show-overflow="none"
                    fixed="left"
                />
                
                <ux-table-column
                    title="序号"
                    type="index"
                    align="center"
                    width="55"
                    fixed
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="acceptCode"
                    title="验收单编号"
                    width="130"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="materialCode"
                    title="设备物资编码"
                    width="110"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="materialName"
                    title="设备物资名称"
                    width="300"
                    :formatter="handleFormatter"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="materialState"
                    title="设备物资说明"
                    width="130"
                    resizable
                >
                    <template slot-scope="{ row }">
                        <el-input v-model="row.materialState" v-if="row.isOtherCost == 1"/>
                        <span v-else>{{ row.materialState }}</span>
                    </template>
                </ux-table-column>
                
                <ux-table-column show-overflow-tooltip field="measureUnit" title="单位" min-width="65" resizable/>
                
                <ux-table-column
                    show-overflow-tooltip
                    field="acceptTime"
                    title="验收日期"
                    width="100"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="unTransportCount"
                    title="剩余可结算数量"
                    width="130"
                    resizable
                />
                
                <!--multiRateCode: 1 0. 是 1.否-->
                <ux-table-column
                    show-overflow-tooltip
                    field="taxRatePercent"
                    title="税率"
                    min-width="100"
                    resizable
                >
                    <template v-slot="{ row }">
                        <el-select
                            v-model="row.taxRateCode"
                            v-if="
                            settlementForm.smpPcConc.multiRateCode == 0 &&
                              row.isOtherCost == 1
                          "
                            @change="
                                data => {
                                  handleTaxRate(data, row);
                                }
                              "
                        >
                            <el-option
                                v-for="item in taxRateOptions"
                                :key="item.dicKey"
                                :label="item.dicValue"
                                :value="item.dicKey"
                            />
                        </el-select>
                        <span v-else>{{
                                (row.taxRatePercent = settlementForm.smpPcConc.multiRateCode
                                    ? settlementForm.smpPcConc.taxRatePercent
                                    : row.taxRatePercent)
                            }}</span>
                    </template>
                </ux-table-column>
                
                <ux-table-column
                    show-overflow-tooltip
                    field="settlementCount"
                    title="结算数量"
                    width="100"
                    resizable
                    :edit-render="{autofocus: '.el-input__inner'}"
                >
                    <template v-slot:edit="{ row }">
                        <el-input
                            v-if="row.isOtherCost == 0 && row.isMerge == 0 && !row.isCategories"
                            v-model="row.settlementCount"
                            @input="check_number(row, 'settlementCount', 3)"
                            @blur="handleNum(row, 'settlementCount', 3)"
                        />
                        <span v-else>{{ row.settlementCount }}</span>
                    </template>
                    <template v-slot="{ row }">
                        <span :class="{'my-input-sc': row.isOtherCost == 0 && row.isMerge == 0 && !row.isCategories}">{{
                                row.settlementCount
                            }}</span>
                    </template>
                </ux-table-column>
                
                <ux-table-column
                    show-overflow-tooltip
                    field="unitPriceWithTax"
                    title="含税单价"
                    width="130"
                    resizable
                    :edit-render="{autofocus: '.el-input__inner'}"
                >
                    <template v-slot:edit="{ row }">
                        <el-input
                            v-if="
                            settlementForm.smpPcConc &&
                              settlementForm.smpPcConc.isFloatContractPrice == 0 &&
                              row.isOtherCost == 0 &&
                              !row.isCategories
                          "
                            v-model="row.unitPriceWithTax"
                            @input="check_number(row, 'unitPriceWithTax', 2)"
                            @blur="handleNum(row, 'unitPriceWithTax', 2)"
                        />
                        <span v-else> {{ row.unitPriceWithTax }}</span>
                    </template>
                    
                    <template v-slot="{ row }">
                        <span :class="{'my-input-sc':settlementForm.smpPcConc &&
                  settlementForm.smpPcConc.isFloatContractPrice == 0 &&
                  row.isOtherCost == 0 &&
                  !row.isCategories}">{{ row.unitPriceWithTax }}</span>
                    </template>
                </ux-table-column>
                <ux-table-column
                    show-overflow-tooltip
                    field="moneyWithTax"
                    title="含税金额"
                    width="130"
                    resizable
                    :edit-render="{autofocus: '.el-input__inner'}"
                >
                    <!--            _item.thirdCategoriesOfCode.substr(0, 4) ==-->
                    <!--            ("1305" || "1306" || "1307" || "1308" || "1309") ||-->
                    <!--            _item.thirdCategoriesOfCode.substr(0, 6) == "990103"-->
                    
                    <template v-slot:edit="{ row }">
                        <el-input
                            v-if="
                            (row.isCategories && row.isCategories == 1) ||
                              row.isOtherCost == 1
                          "
                            v-model="row.moneyWithTax"
                            @input="check_number(row, 'moneyWithTax', 2)"
                            @blur="handleNum(row, 'moneyWithTax', 2)"
                        />
                        <span v-else>{{ row.moneyWithTax }}</span>
                    </template>
                    
                    <template v-slot="{ row }">
                        <span
                            :class="{'my-input-sc':(row.isCategories && row.isCategories == 1) || row.isOtherCost == 1}">{{
                                row.moneyWithTax
                            }}</span>
                    </template>
                </ux-table-column>
                
                <!--                                <ux-table-column-->
                <!--                                    show-overflow-tooltip-->
                <!--                                    field="moneyWithoutTax"-->
                <!--                                    title="不含税金额(元)"-->
                <!--                                    min-width="150"-->
                <!--                                />-->
                
                <ux-table-column
                    show-overflow-tooltip
                    field="brand"
                    title="生产厂家/品牌"
                    width="130"
                    resizable
                >
                    <template v-slot="{ row }">
                        <!--                        <el-input v-if="row.isOtherCost == 0" v-model="row.brand" :disabled=""/>-->
                        <span> {{ row.brand }}</span>
                    </template>
                </ux-table-column>
                
                <!--                <el-table-column-->
                <!--                    show-overflow-tooltip-->
                <!--                    prop="remarks"-->
                <!--                    label="备注"-->
                <!--                    width="100"-->
                <!--                />-->
            </ux-grid>
        </div>
        
        <chooseMaterials
            ref="materialsFormVisible"
            @handleSelect="handleSelect"
            :chooseMaterialsBtn="chooseMaterialsBtn"
        />
    </div>
</template>

<script>
import chooseMaterials from "@/basa/components/public/chooseMaterials";
import jsList from "../js";
import acceptListSelect from "./acceptListSelect";
import {getAcceptanceCert, getTaxRateDict} from "../api/settlement-approval";
import BigNumber from "bignumber.js";
// import { formatNumber } from "@/basa/utils";

export default {
    name: "finaceInfo",
    components: {chooseMaterials, acceptListSelect},
    props: {
        settlementList: {
            type: Array
        },
        settlementForm: {
            type: Object
        }
    },
    // 0 - Math.abs()
    
    data() {
        return {
            summaryBool: false,
            showTableData: [],
            merged: [],
            dialogVisible: false,
            jsList,
            listTableData: [],
            materialVisible: false,
            chooseMaterialsBtn: 0, // 点击选择物资按钮时为true
            checkedLine: [], // 被选中数据
            listId: 0,
            acceptForm: [],
            form: {
                brand: ""
            },
            settlementListInfo: [],
            othersettlementList: [],
            substr: false,
            checkedBefore: [],
            tableMerge: {},
            settlementListArray: [],
            taxRateOptions: [],
            heBingCopy: [],
            tableLoading: false
        };
    },
    // watch() {},
    created() {
        this.getTaxRateDict();
    },
    mounted() {
        let that = this
        
        function mergedJoin(str) {
            let arr = []
            that.settlementList.forEach(obj => {
                if (obj.materialCode + obj.materialState + obj.measureUnit + obj.brand == str) {
                    arr.push(obj.acceptListId)
                }
            })
            return arr.join(',')
        }
        
        if (this.$route.params.id) {
            this.settlementList.forEach(item => {
                if (item.isMainInventory == 1) {
                    item.isMainInventoryMerged = mergedJoin(item.materialCode + item.materialState + item.measureUnit + item.brand)
                }
                if (item.isMerge == 1) {
                    this.merged.push(item.acceptListId);
                }
            });
        }
    },
    activited() {
    },
    update() {
    },
    methods: {
        handleBool(row) {
            console.log(row, '411');
        },
        
        handleTableLoading() {
            this.tableLoading = true;
            
            setTimeout(() => {
                this.tableLoading = false;
            }, 200);
        },
        
        handleSelectableDisabled({row}) {
            
            return row.isCategories !== 1
            
            // row.isCategories
            // if (row.isCategories == 1) return false;
            // return true;
        },
        
        showHeaderBool(n) {
            console.log(n, '__nn');
        },
        handleTaxRate(val, row) {
            let taxRate = this.taxRateOptions.find(e => e.dicKey == val).dicValue;
            taxRate = taxRate == "免税" ? 0 : taxRate.split("%")[0] / 100;
            let taxRatePercent = this.taxRateOptions.find(e => e.dicKey == val)
                .dicValue;
            this.$set(row, "taxRate", taxRate);
            this.$set(row, "taxRa" +
                "tePercent", taxRatePercent);
            
            let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
                .dividedBy(1 + +row.taxRate)
                .toNumber()
                .toFixed(2);
            this.$set(row, "moneyWithoutTax", moneyWithoutTax);
        },
        // 关闭批量操作弹框
        handleClose(done) {
            done();
        },
        //批量修改项确定按钮
        btnModify() {
            this.listTableData.forEach(item => {
                this.$set(item, "brand", this.form.brand);
            });
            this.dialogVisible = false;
        },
        // 汇总
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    // sums[index] = "合计";
                    sums.push("合计");
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr, rowIndex) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            if (column.title == "结算数量") {
                                // if (data[rowIndex].isMainInventory == 1) {
                                //     return prev;
                                // }
                                return new BigNumber(+prev).plus(+curr).toString();
                            } else if (column.title == "含税金额") {
                                if (
                                    data[rowIndex].isMerge == 1 &&
                                    data[rowIndex].isMainInventory == 0
                                ) {
                                    return prev;
                                }
                                return new BigNumber(+prev).plus(+curr).toString();
                            } else {
                                return (prev = " ");
                            }
                        } else {
                            return (prev = " ");
                        }
                    }, 0);
                    // if (column.label == "验收数量") {
                    //   sums[index] = this.numberFilter(sums[index]);
                    // }
                    if (column.title == "结算数量") {
                        sums[index] = (+sums[index]).toFixed(3);
                    }
                    // if (column.label == "含税单价(元)") {
                    //   sums[index] = this.calculateFilter(sums[index]);
                    // }
                    if (column.title == "含税金额") {
                        sums[index] = (+sums[index]).toFixed(2);
                    }
                } else {
                    sums[index] = "";
                }
                // 基本信息的结算数量和结算金额根据结算单明细的结算数量和含税金额同步
                this.settlementForm.currSetCount = sums[10] == 0 ? "" : sums[10];
                this.settlementForm.currSetMoney = sums[12];
            });
            return [sums];
        },
        // 金额四舍五入 8位小数
        calculateFilter(data) {
            if (data || data == 0) {
                if ((data + "").indexOf(".") != -1) {
                    let newData = (data + "").substring(0, (data + "").indexOf(".") + 9);
                    return newData;
                } else {
                    return data;
                }
            } else {
                return "";
            }
        },
        // 金额四舍五入
        numberFilter(data) {
            if (data || data == 0) {
                if ((data + "").indexOf(".") != -1) {
                    let newData = (data + "").substring(0, (data + "").indexOf(".") + 4);
                    return newData;
                } else {
                    return data;
                }
            } else {
                return "";
            }
        },
        // 计算含税金额 start
        check_number(row, prop, num) {
            let reg =
                row.materialName == "价格追跌" ||
                row.materialName == "贴息" ||
                row.materialName == "其他"
                    ? /^-?\d*\.?\d*$/
                    : /^\d*\.?\d*$/;
            if (reg.test(row[prop])) {
                const arr = row[prop].split(".");
                if (arr[arr.length - 1].length > num && arr.length == 2) {
                    row[prop] = row[prop].substr(0, row[prop].length - 1);
                } else if (arr.length == 1 && row[prop].length > 12) {
                    this.$message.warning("整数最多可以输入12位");
                    row[prop] = row[prop].substr(0, row[prop].length - 1);
                }
            } else if (
                row[prop] &&
                reg.test(row[prop].substr(0, row[prop].length - 1))
            ) {
                row[prop] = row[prop].substr(0, row[prop].length - 1);
            } else {
                row[prop] = "";
            }
            // moneyWithoutTax 不含税金额(元) unitPriceWithoutTax 不含税单价(元)
            if (
                row.materialName == "价格追跌" &&
                row[prop][0] != "-" &&
                row[prop] != ""
            ) {
                row[prop] = 0 - Math.abs(+row[prop]);
            }
            
            if (row.settlementCount !== "" && row.unitPriceWithTax !== "") {
                let moneyWithTax = new BigNumber(+row.settlementCount)
                    .multipliedBy(+row.unitPriceWithTax).toFixed(2)
                this.$set(row, "moneyWithTax", moneyWithTax);
                
                let unitPriceWithoutTax = new BigNumber(+row.unitPriceWithTax)
                    .dividedBy(1 + +row.taxRate)
                    .toFixed(2);
                this.$set(row, "unitPriceWithoutTax", unitPriceWithoutTax);
                let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
                    .dividedBy(1 + +row.taxRate)
                    .toFixed(2);
                this.$set(row, "moneyWithoutTax", moneyWithoutTax);
            }
            
            if ((row.isOtherCost && row.taxRate) || row.isCategories) {
                // this.$set(row, "moneyWithTax", row.moneyWithTax);
                
                let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
                    .dividedBy(1 + +row.taxRate)
                    .toFixed(2);
                this.$set(row, "moneyWithoutTax", moneyWithoutTax);
            }
            
        },
        // 计算含税金额 end
        // 其他费用项
        batchOperate(command) {
            // this.othersettlementList = [];
            switch (command) {
                case "btn-interest":
                    this.interest();
                    break;
                case "btn-priceRise":
                    this.priceRise();
                    break;
                case "btn-priceFall":
                    this.priceFall();
                    break;
                case "btn-priceOther":
                    this.priceOther();
                    break;
            }
        },
        // TODO 其他费用项
        // 贴息
        interest() {
            if (
                this.settlementList.find(
                    row => row.materialName == "贴息" && row.isOtherCost == 1
                ) != null
            ) {
                this.$message({
                    type: "warning",
                    message: "该类型已存在"
                });
                return;
            }
            var uuid = this.generateUUID();
            this.settlementList.push({
                mergeUuid: uuid,
                materialName: "贴息",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "贴息",
                costStatus: 1,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                isotherTest: true,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
            this.othersettlementList.push({
                mergeUuid: uuid,
                materialName: "贴息",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "贴息",
                costStatus: 1,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
        },
        // 价格追涨
        priceRise() {
            if (
                this.settlementList.find(
                    row => row.materialName == "价格追涨" && row.isOtherCost == 1
                ) != null
            ) {
                this.$message({
                    type: "warning",
                    message: "该类型已存在"
                });
                return;
            }
            var uuid = this.generateUUID();
            this.settlementList.push({
                mergeUuid: uuid,
                materialName: "价格追涨",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "价格追涨",
                costStatus: 2,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
            this.othersettlementList.push({
                mergeUuid: uuid,
                materialName: "价格追涨",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "价格追涨",
                costStatus: 2,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                isotherTest: true,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
        },
        // 价格追跌
        priceFall() {
            if (
                this.settlementList.find(
                    row => row.materialName == "价格追跌" && row.isOtherCost == 1
                ) != null
            ) {
                this.$message({
                    type: "warning",
                    message: "该类型已存在"
                });
                return;
            }
            var uuid = this.generateUUID();
            this.settlementList.push({
                mergeUuid: uuid,
                materialName: "价格追跌",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "价格追跌",
                costStatus: 3,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
            this.othersettlementList.push({
                mergeUuid: uuid,
                materialName: "价格追跌",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "价格追跌",
                costStatus: 3,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                isotherTest: true,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
        },
        // 其他
        priceOther() {
            if (
                this.settlementList.find(
                    row => row.materialName == "其他" && row.isOtherCost == 1
                ) != null
            ) {
                this.$message({
                    type: "warning",
                    message: "该类型已存在"
                });
                return;
            }
            var uuid = this.generateUUID();
            this.settlementList.push({
                mergeUuid: uuid,
                materialName: "其他",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "其他",
                costStatus: 4,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
            this.othersettlementList.push({
                mergeUuid: uuid,
                materialName: "其他",
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: "其他",
                costStatus: 4,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                isotherTest: true,
                taxRate: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRate / 100
                    : "",
                taxRateCode: this.settlementForm.smpPcConc.multiRateCode
                    ? this.settlementForm.smpPcConc.taxRateCode
                    : ""
            });
        },
        
        // 采购方案选择确认
        programmeConfirm(data) {
        },
        tableRowClassName(data) {
            this.tableMerge = data;
            if (data.row.isMerge == 1 && data.row.isMainInventory == 0) {
                return "hidden-row";
            }
            return "";
        },
        // 选择材料
        handleChooseMaterials() {
            // 打开新增物资清单页面
            this.$refs.materialsFormVisible.dialogFormVisible = true;
            this.chooseMaterialsBtn++;
        },
        // 采购清单选中数据
        listSelectTable(val) {
            this.listTableData = val;
        },
        handleSelect(row) {
        },
        // 选择验收单
        numrow(data) {
            this.settlementList.filter(item => {
                return (
                    item.materialName != "贴息" &&
                    item.materialName != "价格追涨" &&
                    item.materialName != "价格追跌"
                );
            });
            
            let arrId = data.map(e => {
                return e.id;
            });
            this.getAcceptanceCert(arrId);
        },
        getAcceptanceCert(data) {
            getAcceptanceCert({
                ids: data
            }).then(res => {
                var acceptForm = res.data.data;
                for (let i = 0; i < acceptForm.length; i++) {
                    var item = acceptForm[i]; // 接口返回
                    
                    var contract = this.settlementForm.smpPcConc; // 基本信息数据
                    
                    let isFloatContractPrice = this.settlementForm.smpPcConc
                        .isFloatContractPrice;
                    
                    if (this.settlementForm.smpConcMatLessList) {
                        var contractItem = this.settlementForm.smpConcMatLessList.find(
                            data => data.firstId == item.materialFirstId
                        );
                        
                        // if (!isFloatContractPrice) {
                        //     item.unitPriceWithTax = 0;
                        // }
                        
                        if (!contractItem) {
                            item.unitPriceWithTax = "";
                            item.taxRate = "";
                        } else {
                            if (!isFloatContractPrice) {
                                item.unitPriceWithTax = "";
                            } else {
                                item.unitPriceWithTax = contractItem.currentUnitPriceIncludeTax
                                    ? (+contractItem.currentUnitPriceIncludeTax).toFixed(2)
                                    : "";
                            }
                        }
                    }
                    
                    this.$set(
                        item,
                        "taxRate",
                        contract.multiRateCode
                            ? contract.taxRate / 100
                            : contractItem.taxRate
                    );
                    this.$set(
                        item,
                        "taxRateCode",
                        contract.multiRateCode
                            ? contract.taxRateCode
                            : contractItem.taxRateCode
                    );
                    this.$set(
                        item,
                        "taxRatePercent",
                        contract.multiRateCode
                            ? contract.taxRatePercent
                            : contractItem.taxRatePercent
                    );
                    // item.taxRate = this.settlementForm.smpPcConc.taxRate
                    
                    item.isMerge = 0;
                    item.isMainInventory = 0;
                    item.isServices = 0;
                    item.isOtherCost = 0;
                    item.costStatus = 0;
                    
                    // item.unitPriceWithTax = item.unitPriceWithTax? item.unitPriceWithTax : "";
                    item.remarks = item.remake;
                    item.brand = item.manufacturerBrand;
                    item.acceptTime = item.acceptanceDate
                        ? item.acceptanceDate.substr(0, 10)
                        : "";
                    item.acceptCode = item.acceptanceCode;
                    
                    item.acceptNumber = item.acceptanceNumber;
                    
                    item.acceptName = item.acceptanceName;
                    
                    // 修改剩余可结算数量字段 unTransportCount
                    // item.acceptCount = (+item.residualSettlementNumber).toFixed(3);
                    item.unTransportCount = (+item.residualSettlementNumber).toFixed(3);
                    // 修改验收数量字段 acceptCount
                    item.acceptCount = new BigNumber(+item.acceptanceCurrentNumber).minus(+item.bowOutCurrentNumber).toFixed(3);
                    
                    // 结算数量刚进来默认 = 剩余可结算数量
                    item.settlementCount = item.unTransportCount;
                    
                    item.contractId = contract.id;
                    item.contractCode = contract.contractCode;
                    item.contractName = contract.contractName;
                    
                    item.orderCount = item.orderNumber ? (+item.orderNumber).toFixed(3) : "";
                    
                    let moneyWithTax = (
                        item.unitPriceWithTax * item.settlementCount
                    ).toFixed(2);
                    this.$set(item, "moneyWithTax", moneyWithTax);
                    
                    item.moneyWithoutTax = "";
                    item.unitPriceWithoutTax = "";
                    
                    item.acceptId = item.acceptanceId;
                    // 后端新加验收单acceptListId
                    item.acceptListId = item.id;
                    item.firstId = item.materialFirstId;
                    //加mergedId用于判断是否剩余数量被累加
                    item.mergedId = item.id;
                    
                    item.mergeUuid = this.generateUUID();
                    this.settlementList.push(acceptForm[i]);
                    this.check_number(item);
                }
            });
        },
        
        //自动合并settlementList
        hebingFunAuto() {
            this.heBingCopy = JSON.parse(JSON.stringify(this.settlementList));
            let isFloatContractPrice = this.settlementForm.smpPcConc
                .isFloatContractPrice;
            
            function getKey(item) {
                if (isFloatContractPrice) {
                    // 1 固定价
                    return item.materialCode + item.materialName + item.materialState + item.unitPriceWithTax + item.brand + item.taxRatePercent
                } else {
                    return item.materialCode + item.materialName + item.materialState + item.brand + item.taxRatePercent
                }
            }
            
            this.heBingCopy = this.heBingCopy.filter(
                item =>
                    !(
                        (item.isMerge == 1 && item.isMainInventory == 0) ||
                        item.isOtherCost == 1 ||
                        item.isCategories == 1
                    )
            );
            var checkLineCount = {};
            for (var i = 0; i < this.heBingCopy.length; i++) {
                var count = checkLineCount[getKey(this.heBingCopy[i])];
                if (count == null) {
                    checkLineCount[getKey(this.heBingCopy[i])] = 1;
                } else {
                    checkLineCount[getKey(this.heBingCopy[i])] += 1;
                }
            }
            for (var j = 0; j < Object.keys(checkLineCount).length; j++) {
                this.hebingFunAutoAtom(
                    this.heBingCopy.filter(
                        item => getKey(item) == Object.keys(checkLineCount)[j]
                    )
                );
            }
            this.$refs["tableList"].clearSelection();
        },
        // 合并
        hebingFunAutoAtom(checkedLine) {
            checkedLine = checkedLine.filter(
                item => !(item.isMerge == 1 && item.isMainInventory == 0)
            );
            if (checkedLine.length == 1) return;
            // for (var i = 1; i < checkedLine.length; i++) {
            //     if (
            //         checkedLine[0].materialCode != checkedLine[i].materialCode ||
            //         checkedLine[0].materialState != checkedLine[i].materialState ||
            //         checkedLine[0].measureUnit != checkedLine[i].measureUnit ||
            //         checkedLine[0].brand != checkedLine[i].brand ||
            //         checkedLine[0].taxRatePercent != checkedLine[i].taxRatePercent
            //     ) {
            //         this.$message({
            //             type: "warning",
            //             message: "被合并项物资设备编码、说明、单位、厂家、税率必须一致"
            //         });
            //         return;
            //     }
            // }
            
            var settlementCount = 0;
            var moneyWithTax = 0;
            var unTransportCount = 0;
            // var unitPriceWithTax = 0;
            var oldUuidSet = new Set();
            var mergeItem = JSON.parse(JSON.stringify(checkedLine[0]));
            for (let i = 0; i < checkedLine.length; i++) {
                oldUuidSet.add(checkedLine[i].mergeUuid);
                if (checkedLine[i].isMainInventory == 1) {
                    this.settlementList.forEach((item, index) => {
                        if (
                            item.mergeUuid == checkedLine[i].mergeUuid &&
                            item.isMainInventory == 1
                        ) {
                            if (!this.merged.includes(item.mergedId) || unTransportCount == 0) {
                                unTransportCount = (+unTransportCount + +item.unTransportCount).toFixed(3);
                                this.merged.push(item.mergedId);
                            } else {
                                if (Number(unTransportCount) < Number(item.unTransportCount)) {
                                    unTransportCount = item.unTransportCount;
                                }
                            }
                            // acceptCount = (+acceptCount + +item.acceptCount).toFixed(3);
                            moneyWithTax = (+moneyWithTax + +item.moneyWithTax).toFixed(3);
                            this.settlementList.splice(index, 1);
                        }
                    });
                }
            }
            var newUuid = this.generateUUID();
            // 把第一条数据的合并标识位与主数据标识变为1
            mergeItem.isMerge = 1;
            mergeItem.isMainInventory = 1;
            mergeItem.mergeUuid = newUuid;
            
            // var unitPriceWithTax = 0;
            let isMainInventoryMerged = mergeItem.isMainInventoryMerged ? mergeItem.isMainInventoryMerged.split(',') : [];
            for (let i = 0; i < this.settlementList.length; i++) {
                if (!this.settlementList[i].isShow) {
                    if (oldUuidSet.has(this.settlementList[i].mergeUuid)) {
                        this.settlementList[i].isMerge = 1;
                        this.settlementList[i].isMainInventory = 0;
                        if (
                            !this.merged.includes(this.settlementList[i].mergedId) ||
                            unTransportCount == 0
                        ) {
                            unTransportCount = (
                                +unTransportCount + +this.settlementList[i].unTransportCount
                            ).toFixed(3);
                            this.merged.push(this.settlementList[i].mergedId);
                            isMainInventoryMerged.push(this.settlementList[i].mergedId);
                        } else {
                            if (
                                Number(unTransportCount) < Number(this.settlementList[i].unTransportCount)
                            ) {
                                unTransportCount = this.settlementList[i].unTransportCount;
                            }
                        }
                        // acceptCount = (
                        //     +acceptCount + +this.settlementList[i].acceptCount
                        // ).toFixed(3);
                        // this.settlementList[i].acceptCount = 0;
                        settlementCount = (
                            +settlementCount + +this.settlementList[i].settlementCount
                        ).toFixed(3);
                        
                        // 需求 - 合并过的原始数据的结算数量不置为0
                        // this.settlementList[i].settlementCount = 0;
                        
                        // unitPriceWithTax = (+this.checkedLine[0].unitPriceWithTax).toFixed(2);
                        // this.settlementList[i].unitPriceWithTax = 0;
                        moneyWithTax = (
                            +moneyWithTax + +this.settlementList[i].moneyWithTax
                        ).toFixed(2);
                        
                        this.settlementList[i].moneyWithTax = 0; // 必须得等于0，不然合计不正确
                        
                        this.settlementList[i].mergeUuid = newUuid;
                    }
                }
            }
            if (!this.settlementForm.smpPcConc.isFloatContractPrice) {
                mergeItem.unitPriceWithTax = "";
            }
            mergeItem.isMainInventoryMerged = isMainInventoryMerged.join(",");
            mergeItem.acceptCode = "";
            mergeItem.acceptanceCode = "";
            mergeItem.settlementCount = settlementCount;
            mergeItem.moneyWithTax = moneyWithTax;
            mergeItem.unTransportCount = unTransportCount;
            mergeItem.isShow = true;
            this.settlementList.push(mergeItem);
            this.settlementList.splice();
        },
        //删除行
        handleDelete() {
            if (this.checkedLine.length < 1) {
                this.$message.warning("请选择一项");
                return;
            }
            var mergeUuidSet = new Set();
            
            let that = this;
            
            function removeMerged(val) {
                for (var j = 0; j < that.merged.length; j++) {
                    if (that.merged[j] == val) that.merged[j] = "";
                }
            }
            
            
            for (var i = 0; i < this.checkedLine.length; i++) {
                //删除行，去掉已合并的id记录，id为标记是否在结算中参加了剩余可结算量的操作，避免重复剩余可结算量的累加
                if (this.checkedLine[i].isMainInventoryMerged) {
                    
                    this.checkedLine[i].isMainInventoryMerged.split(",").forEach(n => {
                        removeMerged(n);
                    });
                } //删除标记结束
                mergeUuidSet.add(this.checkedLine[i].mergeUuid);
            }
            for (i = this.settlementList.length - 1; i >= 0; i--) {
                if (mergeUuidSet.has(this.settlementList[i].mergeUuid)) {
                    this.othersettlementList.forEach(_item => {
                        if (_item.mergeUuid == this.settlementList[i].mergeUuid) {
                            let condeIndex = this.othersettlementList.indexOf(_item.id);
                            this.othersettlementList.splice(condeIndex, 1);
                        }
                    });
                    this.settlementList.splice(i, 1);
                }
            }
        },
        // 处理input失焦数据格式
        handleNum(row, name, toFix) {
            if (row[name] == "-") return (row[name] = "");
            if (name == "unitPriceWithTax" && row.isMerge == 1 && row.isMainInventory == 1) {
                this.settlementList.map(e => {
                    if (row.mergeUuid == e.mergeUuid) {
                        e.unitPriceWithTax = row.unitPriceWithTax
                    }
                })
            }
            row[name] = (+row[name]).toFixed(toFix);
        },
        // 获取选中
        handleSelectionChange(val) {
            this.checkedLine = val;
        },
        // 复制行
        // handleCopy() {
        //   let checkedData = JSON.parse(JSON.stringify(this.listTableData));
        //   checkedData = checkedData.filter(
        //     item => !(item.isMerge == 1 && item.isMainInventory == 0)
        //   );
        //   if (!checkedData.length) {
        //     this.$message.warning("请选择一项");
        //     return;
        //   }
        //
        //   let checkedFirstMergeUuid;
        //
        //   for (let i = 0; i < checkedData.length; i++) {
        //     checkedFirstMergeUuid = checkedData[i].mergeUuid;
        //     let uuid = this.generateUUID();
        //
        //     for (let j = 0; j < this.settlementList.length; j++) {
        //       if (checkedFirstMergeUuid == this.settlementList[j].mergeUuid) {
        //         let item = JSON.parse(JSON.stringify(this.settlementList[j]));
        //         item.mergeUuid = uuid;
        //         this.settlementList.push(item);
        //       }
        //     }
        //   }
        // },
        
        generateUUID() {
            var d = new Date().getTime();
            var uuid = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (
                c
            ) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
            });
            return uuid;
        },
        handleFormatter({row}) {
            if (
                row.materialName == "贴息" ||
                row.materialName == "价格追涨" ||
                row.materialName == "价格追跌" ||
                row.materialName == "其他" ||
                (row.categoryCode &&
                    row.categoryCode.substr(0, 4) ==
                    ("1305" || "1306" || "1307" || "1308" || "1309")) ||
                row.categoryCode.substr(0, 6) == "990103"
            ) {
                let arr = ["unTransportCount", "settlementCount", "unitPriceWithTax"];
                arr.forEach(e => {
                    row[e] = "";
                });
            }
            return row.materialName;
        },
        getTaxRateDict() {
            getTaxRateDict({}).then(res => {
                this.taxRateOptions = res.data.data;
            });
        },
        
        handleTable() {
            if (this.settlementList.length) {
                let yunshu = [], // 运输类
                    hebingqian = [], // 没有合并的数据
                    hebinghou = [], // 合并后隐藏的数据
                    hebingMerge = [], // 合并后生成的数据
                    qita = []; // 其他类数据
                this.settlementList.map(e => {
                    if (e.isCategories && e.isCategories == 1) {
                        yunshu.push(e);
                    } else if (e.isMerge == 0 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebingqian.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebinghou.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 1 && e.isOtherCost == 0) {
                        hebingMerge.push(e);
                    } else if (e.isOtherCost && e.isOtherCost == 1) {
                        qita.push(e);
                    }
                });
                let tableData = [...hebingqian, ...hebingMerge, ...yunshu, ...qita];
                this.$refs["tableList"].reloadData(tableData);
                // this.showTableData = ;
            } else {
                this.$refs["tableList"].reloadData([]);
            }
        },
        // 结算数量 v-if
        // handleNumCurrent(row) {
        //     if (row.thirdCategoriesOfCode && (row.thirdCategoriesOfCode.substr(0, 4) == '1305' ||
        //         row.thirdCategoriesOfCode.substr(0, 4)== '1306' ||
        //         row.thirdCategoriesOfCode.substr(0, 4) == '1307' ||
        //         row.thirdCategoriesOfCode.substr(0, 4) == '1308' ||
        //         row.thirdCategoriesOfCode.substr(0, 4) == '1309' ||
        //         row.thirdCategoriesOfCode.substr(0, 6) == '990103')) {
        //         return false;
        //     } else if (row.isOtherCost == 0 && row.isMerge == 0) {
        //         return true;
        //     } else {
        //         return false;
        //     }
        //
        //     // // (row.isOtherCost == 0 && row.isMerge == 0) &&
        //     // // row.thirdCategoriesOfCode &&
        //     // "
        // }
        
        
    },
    computed: {},
    watch: {
        settlementList(n) {
            this.handleTable();
            this.showHeaderBool(n);
        }
    }
};
</script>

<style lang="scss" scoped>
/deep/ .ccui-multifunctional-table-wrapper {
    .el-table td,
    .el-table th.is-leaf {
        border-right: 1px solid #edf2fc;
    }
}

.ml {
    margin-left: 10px;
}

.operation-group {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 20px;
}

/deep/
.ccui-multifunctional-table-wrapper
.el-table
tbody
tr
td:first-child
.cell {
    border-right: 1px solid #f1f1f1;
}

.deleteLine {
    padding: 0 20px;
    height: 30px;
    background: #f7f9ff;
    border: 1px solid #0089ef;
    border-radius: 4px;
    position: relative;
    color: #0089ef;
    margin-left: 10px;
}

/deep/ .hidden-row {
    display: none;
}

/deep/ .el-dropdown {
    margin-right: 10px;
    
    button {
        background: #f7f9ff;
        border: 1px solid #0089ef;
        color: #0089ef;
    }
}

/deep/ .el-form-item__content .el-input {
    width: 167px;
}

/deep/ .el-table__fixed-header-wrapper {
    th {
        pointer-events: auto;
    }
}

/deep/ .el-table__fixed,
/deep/ .el-table__fixed-right {
    pointer-events: none;
    
    td {
        pointer-events: auto;
    }
}
</style>
